<?php

namespace app\controllers;

use app\librarys\Fanso2oInteface;
use app\librarys\Huafeiduo;
use app\librarys\Inteface;
use app\librarys\Tools;
use app\models\Card;
use app\models\GoodsVisitLog;
use app\models\Institution;
use app\models\MallExceptionLog;
use app\models\MallFrontEnd;
use app\models\MallOperateLog;
use app\models\Pay;
use app\models\Voucher;
use Yii;
use yii\data\Pagination;
use app\models\Goods;
use app\models\Mall;
use yii\base\InvalidParamException;
use yii\web\Controller;
use app\models\Cart;
use app\models\User;
use app\models\Address;
use app\models\Information;
use app\models\Order;
use app\models\Integral;
use app\models\Area;

/**
 * PC版商城
 * Class MallController
 * @package app\controllers
 */
class MallController extends Controller
{
    public $enableCsrfValidation = false;
    public $layout = 'mall_layout';

    public $navTag = '';  // index, goods_list, ..., user

    public function beforeAction($action)
    {
        $isRecordLog = \Yii::$app->params['isRecordLog'];
        $logId = '';
        if ($isRecordLog == true) {
            // 记录请求日志
            $institution_code = null;
            $institution_name = null;

            $logId = MallOperateLog::add(
                $action->controller->id,
                $action->id,
                $_GET,
                $_POST,
                Mall::getCurrentUserId(),
                Mall::getCurrentUserName(),
                $institution_code,
                $institution_name,
                $_SERVER['REMOTE_ADDR'],
                $_SERVER['HTTP_USER_AGENT'],
                $_SERVER['REQUEST_TIME']
            );
            \Yii::$app->session->set('request_mall_operate_log_id', $logId);
            \Yii::$app->session->set('request_mall_timestamp', Tools::getMillisecond());
        }

        Mall::setCurrentInstitution();

        //获取机构信息进行日志更新
        $currentInstitution = \Yii::$app->session->get(Mall::SessionKey_CurrentInstitution);
        if ($currentInstitution != null && $isRecordLog == true) {
            $institution_code = $currentInstitution['code'];
            $institution_name = $currentInstitution['name'];
            MallOperateLog::setInstitution($logId, $institution_code, $institution_name);
        }

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function runAction($id, $params = [])
    {
        try {
            return parent::runAction($id, $params);
        } catch (\Exception $ex) {
            $isRecordLog = \Yii::$app->params['isRecordLog'];
            if ($isRecordLog == true) {
                // 记录异常日志
                $logId = \Yii::$app->session->get('request_mall_operate_log_id');
                if ($logId != null) {
                    MallOperateLog::setException($logId, $ex);

                    $operateLog = MallOperateLog::getById($logId);
                    if ($operateLog != null) {
                        $currentInstitution = \Yii::$app->session->get(Mall::SessionKey_CurrentInstitution);

                        $institution_code = null;
                        $institution_name = null;

                        if ($currentInstitution != null) {
                            $institution_code = $currentInstitution['code'];
                            $institution_name = $currentInstitution['name'];
                        }

                        MallExceptionLog::add(
                            $operateLog->controllerId,
                            $operateLog->actionId,
                            $operateLog->getParams,
                            $operateLog->postParams,
                            $operateLog->userId,
                            $operateLog->userName,
                            $institution_code,
                            $institution_name,
                            $operateLog->remoteAddr,
                            $operateLog->httpUserAgent,
                            $operateLog->createDatetime,
                            $ex
                        );
                    }
                }
            }

            throw $ex;
        }
    }

    public function afterAction($action, $result)
    {
        $isRecordLog = \Yii::$app->params['isRecordLog'];
        if ($isRecordLog == true) {
            // 记录请求总共耗时(毫秒)
            $logId = \Yii::$app->session->get('request_mall_operate_log_id');
            if ($logId != null) {
                $time = Tools::getMillisecond();
                $time = $time - \Yii::$app->session->get('request_mall_timestamp');
                MallOperateLog::setDurationTime($logId, $time);
            }
        }

        return parent::afterAction($action, $result);
    }


    public function actionLogin()
    {
        $this->layout = false;

        $returnUrl = \Yii::$app->request->get('return_url', 'index?institution_code=' . Mall::getCurrentInstitutionCode());
        $returnUrl = urldecode($returnUrl);

        if (\Yii::$app->request->isPost == true) {
            $phone = \Yii::$app->request->post('phone');
            $verificationCode = \Yii::$app->request->post('verification_code');
            $user = User::loginWithPhone(Mall::getCurrentInstitutionCode(), $phone, $verificationCode);
            if ($user != null) {
                if ($user['is_enabled'] == 0) {
                    throw new \Exception('此用户已被禁用!');
                }
                Mall::setCurrentUser($user);
                return $this->redirect($returnUrl);
            }
        }

        return $this->render('login', ['return_url' => $returnUrl]);
    }

    public function actionSendLoginSmsVerificationCodeHandler()
    {
        $phone = \Yii::$app->request->post('phone');
        try {
            $user = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $phone);
            if ($user == null) {
                throw new \Exception('此机构无此用户!');
            }

            if ($user['is_enabled'] == 0) {
                throw new \Exception('此用户已被禁用!');
            }

            User::sendSmsVerificationCode($phone);
            return $this->renderJson();
        } catch (\Exception $ex) {
            return $this->renderJson(null, 1, $ex->getMessage());
        }
    }

    public function actionLogout()
    {
        Mall::userLogout();
        Mall::removeCurrentCard();
        Mall::removeCurrentVoucher();
        self::removeCardSession();
        $returnUrl = \Yii::$app->request->get('return_url', 'index?institution_code=' . Mall::getCurrentInstitutionCode());
        return $this->redirect($returnUrl);
    }

    private function removeCardSession()
    {
        Yii::$app->session->remove('index-card-show');
        Yii::$app->session->remove('index-card-id');
    }

    public function actionOrderList()
    {
        self::loginAuth();
        $this->navTag = 'user';
        return $this->render('order-list');
    }

    public function actionOrderListPartView()
    {
        self::loginAuth();
        $userId = Mall::getCurrentUserId();
        $page = 1;
        $pageSize = 10000;
        $maxPage = 1;
        $items = Order::getListByUser($userId, ($page - 1) * $pageSize, $pageSize);
        if ($items != null && $items != '') {
            for ($i = 0; $i < count($items); $i++) {
                $goodsitems = Order::getGoodsDetail($items[$i]['id']);
                if ($goodsitems != null && $goodsitems != '') {
                    $items[$i]['goods_list'] = $goodsitems;

                    $total_quantity = 0;
                    foreach ($goodsitems as $goods) {
                        $total_quantity = $total_quantity + $goods['quantity'];
                    }
                    $items[$i]['total_quantity'] = $total_quantity;
                } else {
                    $items[$i]['goods_list'] = null;
                    $items[$i]['total_quantity'] = null;
                }
            }
        }

        return $this->renderPartial('order-list-part-view', ['items' => $items, 'page' => $page, 'max_page' => $maxPage]);
    }


    /**
     * 获得地区三级体系 get-area-handler
     */
    public function actionGetAreaHandler()
    {
        $request = Yii::$app->request;
        $parent_id = $request->post("parent_id");

        $others = Area::getAreaList($parent_id);

        return $this->renderJson(['others' => $others]);
    }

    public function actionUserAddress()
    {
        self::loginAuth();
        $this->navTag = 'user';

        $userId = Mall::getCurrentUserId();
        $addressList = Address::getUserAllAddress($userId);
        return $this->render('user-address', ['address_list' => $addressList]);
    }

    public function actionUserAddressPartView()
    {
        self::loginAuth();
        $userId = Mall::getCurrentUserId();
        $addressId = \Yii::$app->request->post('address_id');
        $item = null;
        if ($addressId != null && $addressId != '') {
            $item = Address::getDetail($addressId);
        }
        return $this->renderPartial('user-address-part-view', ['item' => $item]);
    }

    public function actionSaveUserAddressHandler()
    {
        self::loginAuth();
        $userId = Mall::getCurrentUserId();
        $addressId = \Yii::$app->request->post('address_id');
        $name = \Yii::$app->request->post('name');
        $phone = \Yii::$app->request->post('phone');
        $provinceName = \Yii::$app->request->post('province_name');
        $cityName = \Yii::$app->request->post('city_name');
        $regionName = \Yii::$app->request->post('region_name');
        $address = \Yii::$app->request->post('address');
        $remark = \Yii::$app->request->post('remark');

        if ($addressId == null || $addressId == '') {
            $addressId = 0;
        }
        $rt = Address::saveAddress($userId, $addressId, $name, $phone, $provinceName, $cityName, $regionName, $address, $remark);

        return $this->renderJson();
    }

    public function actionSetDefaultAddressHandler()
    {
        self::loginAuth();
        $userId = Mall::getCurrentUserId();
        $addressId = \Yii::$app->request->post('address_id');
        $rt = Address::setDefault($userId, $addressId);
        return $this->renderJson(null, $rt);
    }

    public function actionDeleteAddressHandler()
    {
        self::loginAuth();
        $addressId = \Yii::$app->request->post('address_id');
        $userId = Mall::getCurrentUserId();
        $rt = Address::deleteAddress($userId, $addressId);
        return $this->renderJson();
    }

    public function actionUserInformation()
    {
        self::loginAuth();
        $this->navTag = 'user';

        $userId = Mall::getCurrentUserId();
        $userInfo = User::getUserDetail($userId);
        return $this->render('user-information', ['user_info' => $userInfo]);
    }

    public function actionSaveUserInformation()
    {
        self::loginAuth();
        $userId = Mall::getCurrentUserId();
        $name = \Yii::$app->request->post('name');
        $phone = \Yii::$app->request->post('phone');
        $rt = User::setUserName($userId, $name, $phone);
        return $this->renderJson();
    }

    public function actionUserCard()
    {
        self::loginAuth();
        $this->navTag = 'user';

        $userId = Mall::getCurrentUserId();
        $userInfo = User::getUserDetail($userId);
        return $this->render('user-card', ['user_info' => $userInfo]);
    }

    public function actionUserPresent()
    {
        self::loginAuth();
        $this->navTag = 'user';

        $userId = Mall::getCurrentUserId();
        $userInfo = User::getUserDetail($userId);
        return $this->render('user-present', ['user_info' => $userInfo]);
    }

    /**
     * 积分转增
     * @return string
     */
    public function actionIntegralTransferHandler()
    {
        self::loginAuth();
        $msg = "";
        $flag = 0;
        $request = Yii::$app->request;
        $number = $request->post("number");
        $integral = $request->post("integral");


        $loginuser = Mall::getCurrentUser();
        if ($loginuser == null || $loginuser == '') {
            $flag = 1;
            $msg = "请先登陆";
        } else {

            if (($number != null && $number != '') && ($integral != null && $integral != '' && intval($integral) > 0)) {
                $into_user = User::getUserByPhone(Mall::getCurrentInstitutionCode(), $number);

                if ($number == $loginuser['phone']) {
                    $flag = 1;
                    $msg = "不能转增给自己";
                } else if ($into_user == null || $into_user == '') {
                    $flag = 1;
                    $msg = "对方用户不存在";
                } else if ($into_user['is_enabled'] == 0) {
                    $flag = 1;
                    $msg = "对方用户已被禁用";
                } else {
                    $rtvalue = User::integralTransfer($loginuser['id'], $into_user['id'], $integral);
                    if ($rtvalue == 1) {
                        $flag = 1;
                        $msg = "系统异常请重试";
                    } else if ($rtvalue == 20) {
                        $flag = 1;
                        $msg = "当前余额不足";
                    }
                }
            }
        }

        return $this->renderJson(null, $flag, $msg);
    }

    public function actionUserAccountRecord()
    {
        self::loginAuth();
        $this->navTag = 'user';

        $userId = Mall::getCurrentUserId();
        $page = \Yii::$app->request->get('page', 1);
        $pageSize = \Yii::$app->request->get('page_size', 8);
        $recordType = \Yii::$app->request->get('record_type', 0);
        $startDate = \Yii::$app->request->get('start_date', '');
        $endDate = \Yii::$app->request->get('end_date', '');

        if ($page <= 0) {
            $page = 1;
        }

        $items = Integral::getIntegralRecordListByUser(($page - 1) * $pageSize, $pageSize, $userId, $recordType, $startDate, $endDate);

        $dataCount = Integral::getIntegralRecordCountByUser($userId, $recordType, $startDate, $endDate);
        if ($dataCount % $pageSize > 0) {
            $maxPage = intval($dataCount / $pageSize) + 1;
        } else {
            $maxPage = intval($dataCount / $pageSize);
        }

        //查询用户剩余积分
        $userintegral = Integral::getUserIntegral($userId);

        return $this->render('user-account-record', ['items' => $items, 'userintegral' => $userintegral, 'page' => $page, 'max_page' => $maxPage, 'record_type' => $recordType, 'start_date' => $startDate, 'end_date' => $endDate]);

    }

    public function actionUserInstitutionInfo()
    {
        return Mall::getCurrentInstitution();
    }

//
//    public function actionLogout()
//    {
//        Mall::userLogout();
//        $returnUrl = \Yii::$app->request->get('return_url', 'index');
//        return $this->redirect($returnUrl);
//    }


    public function actionApplyForInstitution()
    {
        $this->layout = false;
        return $this->render('apply-for-institution');
    }

    public function actionApplyForInstitutionForm()
    {
        $data = null;
        $status = 0;
        $message = '';

        $request = \Yii::$app->request;
        $phone = $request->post('txtContacterPhone');
        $verificationCode = $request->post('txtVerificationCode');
        $phoneAuth = User::authSmsVerificationCode($phone, $verificationCode);
        if ($phoneAuth == true) {
            $applyData = $request->post();
            $applyData['parentCode'] = \Yii::$app->params['xt.institution.code']; // 创建机构(PC试用,挂在鑫泰下级,parentCode固定为JG000002)
            if (Mall::applyForInstitution($applyData, $message, 'xt')) {
                $data =
                    [
                        'account' => $phone,
                        'password' => $applyData['password'],
                        'record_id' => $applyData['record_id'],
                        'institution_code' => $applyData['institution_code']
                    ];
            } else {
                $status = 1;
            }
        } else {
            $status = 1;
            $message = '验证码错误';
        }
        return $this->renderJson($data, $status, $message);
    }

    public function actionApplyForInstitutionSuccess()
    {
        $this->layout = false;

        $request = \Yii::$app->request;
        $account = $request->get('account');
        $password = $request->get('password');
        $record_id = $request->get('record_id');
        $institution_code = $request->get('institution_code');
        return $this->render('apply-for-institution-success',
            [
                'account' => $account,
                'password' => $password,
                'record_id' => $record_id,
                'institution_code' => $institution_code
            ]);
    }

    public function render($view, $params = [])
    {
        $currentInstitution = null;
        try {
            $currentInstitution = Mall::getCurrentInstitution();
        } catch (\Exception $e) {
            $currentInstitution = null;
        }
        $theme = $currentInstitution == null ? '' : $currentInstitution['theme_pc'];
        try {
            if (empty($theme)) {
                return parent::render($view, $params);
            } else {
                return parent::render("theme-$theme/$view", $params);
            }
        } catch (InvalidParamException $ex) {
            return parent::render($view, $params);
        }
    }

    public function renderPartial($view, $params = [])
    {
        $currentInstitution = null;
        try {
            $currentInstitution = Mall::getCurrentInstitution();
        } catch (\Exception $e) {
            $currentInstitution = null;
        }
        $theme = $currentInstitution == null ? '' : $currentInstitution['theme_pc'];
        try {
            if (empty($theme)) {
                return parent::renderPartial($view, $params);
            } else {
                return parent::renderPartial("theme-$theme/$view", $params);
            }
        } catch (InvalidParamException $ex) {
            return parent::renderPartial($view, $params);
        }
    }

    public function renderJson($data = null, $status = 0, $message = 'success')
    {
        $result = [
            'status' => $status,
            'message' => $message,
            'data' => $data
        ];

        return json_encode($result, true);
    }

    /**权限校验
     * @return mixed
     */
    private function loginAuth()
    {
        $user = Mall::getCurrentUser();
        if ($user == null) {

            if (strpos($_SERVER['HTTP_ACCEPT'], "application/json") === false) {

                $loginUrl = "login?return_url=" . urlencode(Yii::$app->request->absoluteUrl);
                // return $this->redirect($loginUrl);
                Header("Location:$loginUrl");
                exit;
            } else {
                $loginUrl = "login?return_url=" . urlencode($_SERVER['HTTP_REFERER']);
                echo $this->renderJson(['loginUrl' => $loginUrl], -1);
                exit;
            }

        }
//        var_dump($user);exit;
        return $user;
    }

    public function actionIndex($card_id = false)
    {
        $this->navTag = 'index';
        $institutionCode = Mall::getCurrentInstitutionCode();
        $user = Mall::getCurrentUser();
        //分类
        $categoryList = MallFrontEnd::getGoodsCategoryLv1($institutionCode);
        foreach ($categoryList as &$item1) {
            $categoryLv2 = MallFrontEnd::getGoodsCategoryNextLv($institutionCode, $item1['code']);
            $item1['categoryLv2'] = $categoryLv2;
            foreach ($item1['categoryLv2'] as &$item2) {
                $item2['categoryLv3'] = MallFrontEnd::getGoodsCategoryNextLv($institutionCode, $item2['code']);
            }
        }
        //特价专区
        $activityBargainList = MallFrontEnd::getActivityBargainList($institutionCode);
        $bargainGoodsList = MallFrontEnd::getBargainTopGoodsListByInstitution($institutionCode);
        //热销产品
        $hotGoodsList = MallFrontEnd::getHotGoodsList($institutionCode);
        //活动分类
        $extendCategoryList = MallFrontEnd::getGoodsExtendCategoryList($institutionCode);
//        var_dump($bargainGoodsList);exit;
        //卡片
        $cardGoodsList = [];
        $is_card_show = true;
        $card_id = Yii::$app->session->get('index-card-id', $card_id);
        if ($card_id && $user) {
            Yii::$app->session->set('index-card-id', $card_id);
            $is_card_show = Yii::$app->session->get('index-card-show', true);
            if ($is_card_show) {
                Yii::$app->session->set('index-card-show', false);
            }
            $cardGoodsList = Card::getCardSelectedGoodsById($card_id);
            foreach ($cardGoodsList as &$item) {
                $images = Goods::getGoodsImage($item['goods_code'], 1);
                if (count($images) > 0) {
                    $item['image'] = $images[0]['image_url'];
                } else {
                    $item['image'] = '';
                }
            }
        }
        if ($user) {
            Yii::$app->session->set('normal-login-phone', $user['phone']);
        }
//        var_dump($user);exit;
        return $this->render('index',
            [
                'categoryList' => $categoryList,
                'activityBargainList' => $activityBargainList,
                'bargainGoodsList' => $bargainGoodsList,
                'hotGoodsList' => $hotGoodsList,
                'extendCategoryList' => $extendCategoryList,
                'cardGoodsList' => $cardGoodsList,
                'is_card_show' => $is_card_show,
            ]);
    }

    /**
     * 商品列表
     * cv  展示形式
     * @return string
     * 4的倍数
     * 36
     */
    public function actionGoodsList($cv = 0, $page = 1, $pageSize = 20)
    {
        $institution_code = Mall::getCurrentInstitutionCode();//机构
        $goodsListTitle = Yii::$app->request->get('goodsListTitle', '');//页面搜索标题
        $page = is_numeric($page) ? $page : 1;
        $goodsListTitle = Yii::$app->request->get('goodsListTitle', '');//页面搜索标题
        //条件
        $goodsCode = Yii::$app->request->get('goodsCode', '');//产品代码
        $goodsName = Yii::$app->request->get('goodsName', '');//产品名称
        $goodsCategoryCode = Yii::$app->request->get('goodsCategoryCode', '');//商品类别
        $goodsExtendCategoryCode = Yii::$app->request->get('goodsExtendCategoryCode', '');//商品扩展类别
        $isActivity = Yii::$app->request->get('isActivity', '0');//是否活动产品
        $isNewest = Yii::$app->request->get('isNewest', null);//是否新品
        $isHot = Yii::$app->request->get('isHot', null);//是否热销
        $integralFrom = Yii::$app->request->get('integralFrom', null);//最小积分
        $integralTo = Yii::$app->request->get('integralTo', null);//最大积分
        //排序
        $sort = Yii::$app->request->get('sort', 0);//排序

        //取得产品总数
        $dataCount = MallFrontEnd::getGoodsListBySearch($institution_code, $goodsCode, $goodsName, $goodsCategoryCode, $goodsExtendCategoryCode, $isActivity, $isNewest, $isHot, $integralFrom, $integralTo, $sort);
//        var_dump($dataCount);exit;
        if ($dataCount % $pageSize > 0) {
            $maxPage = intval($dataCount / $pageSize) + 1;
        } else {
            $maxPage = intval($dataCount / $pageSize);
        }
        if ($page > $maxPage) {
            $page = $maxPage;
        }
        //查询结果
        $list = MallFrontEnd::getGoodsListBySearch($institution_code, $goodsCode, $goodsName, $goodsCategoryCode, $goodsExtendCategoryCode, $isActivity, $isNewest, $isHot, $integralFrom, $integralTo, $sort, false, $page, $pageSize);


        //返回结果
        return $this->render('goods-list', [
            'items' => $list,
            'page' => $page,
            'maxPage' => $maxPage,
            'sort' => $sort,
            'goodsListTitle' => $goodsListTitle,
            'cv' => $cv,
            //条件
            'goodsCode' => $goodsCode,
            'goodsName' => $goodsName,
            'goodsCategoryCode' => $goodsCategoryCode,
            'goodsExtendCategoryCode' => $goodsExtendCategoryCode,
            'isActivity' => $isActivity,
            'isNewest' => $isNewest,
            'isHot' => $isHot,
            'integralFrom' => $integralFrom,
            'integralTo' => $integralTo
        ]);
    }

    /**商品详情
     * @param string $goods_code
     * @return string
     */
    public function actionGoodsDetail($goods_code = '')
    {
        $goodsCode = $goods_code;
        if (!empty($goodsCode)) {
            $institutionCode = Mall::getCurrentInstitutionCode();//机构
            $goods = MallFrontEnd::getGoodsDetail($institutionCode, $goodsCode);
            if ($goods) {
                // $goods['stock'] = MallFrontEnd::getGoodsStock($goodsCode);
            } else {
                echo 'goods_code not found!';
                exit;
            }
            $cartGoodsCount = 0;
            $user = Mall::getCurrentUser();
            $userId = null;
            if ($user) {
                $userId = $user['id'];
                $cartGoodsCount = MallFrontEnd::getCartGoodsCount($userId);
            }

            try {
                GoodsVisitLog::add($goodsCode, $userId, $institutionCode);  // 商品访问记录,以便统计商品受关注程度
            } catch (\Exception $e) {
            }
//var_dump($goods);exit;
            return $this->render('goods-detail',
                [
                    'goods' => $goods,
                    'cartGoodsCount' => $cartGoodsCount,
                ]);
        }
    }

    /**虚拟券列表
     * @param int $page
     * @param int $pageSize
     * @param string $tagName
     * @return string
     */
    public function actionVirtualCouponList($page = 1, $pageSize = 10, $tagName = 'all')
    {
        $this->navTag = 'virtual-coupon-list';
        if ($tagName == 'all') {
            $result = Fanso2oInteface::helper_getAllGoodsList($page, $pageSize);
        } else {
            $result = Fanso2oInteface::helper_getCategoryGoodsList($tagName, $page, $pageSize);
        }
//        var_dump($goodsList);        exit;
        return $this->render('virtual-coupon-list', [
            'result' => $result,
        ]);
    }

    /**虚拟券详情
     * @param $shopId
     * @return string
     * @throws \Exception
     */
    public function actionVirtualCouponDetail($shopId)
    {
        $this->navTag = 'virtual-coupon-list';
        $goodsList = Fanso2oInteface::helper_getGoodsListByShopIdList([$shopId]);
        if (count($goodsList) == 0) {
            throw new \Exception("没有此卡券");
        }
        $goods = $goodsList[0];
        //适用地区
        $districtList = [];
        foreach ($goods['info']->district as $item) {
            $districtList[] = $item->name;
        }
        $goods['districtStr'] = implode(',', $districtList);
//        var_dump($goodsList);        exit;
        return $this->render('virtual-coupon-detail', [
            'goods' => $goods,
        ]);
    }

    /**
     * 获取库存
     * get-goods-stock-handle
     */
    public function actionGetGoodsStockHandle()
    {
        $goodsCode = \Yii::$app->request->post('goodsCode');
        $stock = 0;
        if ($goodsCode) {
            $stock = MallFrontEnd::getGoodsStock($goodsCode);
        }

        return $this->renderJson($stock, 0, '');
    }

    /**
     * 获取历史足迹商品
     * @return string
     */
    public function actionGetHisGoodsHandler()
    {
        $institution_code = Mall::getCurrentInstitutionCode();//机构
        $goods_code_list = \Yii::$app->request->post('goods_code_list');
        $goods_codes = '';

        for ($i = 0; $i < count($goods_code_list); $i++) {
            $goods_codes = $goods_codes . '\'' . $goods_code_list[count($goods_code_list) - 1 - $i] . '\',';
        }

        $goods_codes = substr($goods_codes, 0, strlen($goods_codes) - 1);
        $items = MallFrontEnd::getHisGoodsList($institution_code, $goods_codes);
        return $this->renderJson($items, 0, '');
    }

    //添加商品到购物车 add-cart-handle
    public function actionAddCartHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        $goodsCode = Yii::$app->request->post('goodsCode');
        $quantity = Yii::$app->request->post('quantity');
        $card_id = MallFrontEnd::addCart($userId, $goodsCode, $quantity);
        return $this->renderJson(['card_id' => $card_id]);
    }

    /**
     * 获取购物车产品数量
     * get-cart-goods-count
     */
    public function actionGetCartGoodsCount()
    {
        $cartGoodsCount = 0;
        $user = Mall::getCurrentUser();
        $userId = null;
        if ($user) {
            $userId = $user['id'];
            $cartGoodsCount = MallFrontEnd::getCartGoodsCount($userId);
        }
        return $this->renderJson([$cartGoodsCount]);
    }

    //修改某用户购物车中商品数 set-cart-quantity-handle
    public function actionSetCartQuantityHandle()
    {

        $user = self::loginAuth();
        $userId = $user['id'];
        $cartId = Yii::$app->request->post('cartId');
        $quantity = Yii::$app->request->post('quantity');
        MallFrontEnd::setCartQuantity($userId, $cartId, $quantity);
        return $this->renderJson([]);
    }

    //设置购物车商品选择状态 set-cart-selected-handle
    public function actionSetCartSelectedHandle()
    {

        $user = self::loginAuth();
        $userId = $user['id'];
        $cartId = Yii::$app->request->post('cartId');
        $isSelected = Yii::$app->request->post('isSelected');
        MallFrontEnd::setCartSelected($userId, $cartId, $isSelected);
        return $this->renderJson([]);
    }

    //移除某用户购物车中的某件商品 remove-cart-handle
    public function actionRemoveCartHandle()
    {

        $user = self::loginAuth();
        $userId = $user['id'];
        $cartId = Yii::$app->request->post('cartId');
        MallFrontEnd::removeCart($userId, $cartId);
        return $this->renderJson([]);
    }

    public function actionCart()
    {
        $user = self::loginAuth();
        $institutionCode = Mall::getCurrentInstitutionCode();
        $userId = $user['id'];
        $isLogin = true;
        $cartList = MallFrontEnd::getCart($userId);
        //获取库存
        foreach ($cartList as &$item) {
            $item['stock'] = MallFrontEnd::getGoodsStock($item['goods_code']);
        }
//            var_dump($cartList);exit;
        $hotGoosList = MallFrontEnd::getHotGoodsList($institutionCode);//热销产品
        return $this->render('cart', [
            'hotGoosList' => $hotGoosList,
            'cartList' => $cartList,
        ]);
    }

    public function actionOrderDetail($orderId = false, $orderCode = false)
    {
        $user = self::loginAuth();
        $this->navTag = 'user';
        $userId = $user['id'];
        if ($orderCode == false && $orderId == false) {
            throw new \Exception('param error!');
        }
        if ($orderId) {
            $orderInfo = MallFrontEnd::getOrderById($orderId);
            if ($orderInfo == false) {
                throw new \Exception('order not found!1');
            }
            $orderCode = $orderInfo['code'];
        }
        self::authOrder($orderCode);
        $orderInfo = MallFrontEnd::getOrderByCode_detail($orderCode);
        if ($orderInfo == false) {
            echo "order not found!";
            exit;
        }
        $orderDeliveryList = [];
        $all_stock_status = 1;
        if ($orderInfo['status'] == '1') {//订单未支付
            /**
             * 更新未支付订单信息
             * ps:商品不能购买了:quantity数量设为0
             * ps:订单总价为0:订单状态设置为无效
             */
            MallFrontEnd::updateOrder($orderInfo['id']);
            //重新获取订单信息
            $orderInfo = MallFrontEnd::getOrderByCode_detail($orderCode);
            $orderGoodsList = MallFrontEnd::getOrderGoodsDetail($orderInfo['id'], $orderInfo['institution_code']);
            //库存信息/quantity
            foreach ($orderGoodsList as &$item) {
                $item['stock'] = MallFrontEnd::getGoodsStock($item['goods_code']);
                if ($item['stock'] < $item['quantity']) {
                    $all_stock_status = 0;
                }
            }
        } else {
            $orderGoodsList = MallFrontEnd::getOrderGoodsDetail($orderInfo['id'], $orderInfo['institution_code']);
            $orderDeliveryList = MallFrontEnd::getOrderDelivery($orderCode);
            $item['goods_list'] = [];
            foreach ($orderDeliveryList as &$item) {
                $item['goods_list'] = MallFrontEnd::getOrderDeliveryDetailGoodsList($item['id']);
            }
        }
//var_dump($orderInfo);exit;
        $orderInfo['orderStatusTxt'] = MallFrontEnd::orderStatusToUserTxt($orderInfo['status']);
        $userIntegral = User::getUserIntegral($userId);
        return $this->render('order-detail', [
            'orderInfo' => $orderInfo,
            'orderGoodsList' => $orderGoodsList,
            'orderDeliveryList' => $orderDeliveryList,
            'userIntegral' => $userIntegral,
            'all_stock_status' => $all_stock_status,

        ]);
    }
    //获取物流信息详情
    //delivery-detail-part-view
    public function actionDeliveryDetailPartView()
    {
        $logistics_code = Yii::$app->request->post('logistics_code', false);
        $track_record = null;
        if ($logistics_code) {
            $expressTrack = Inteface::getExpressTrackRecord($logistics_code);
            if ($expressTrack != null && $expressTrack != '') {
                $track_record = $expressTrack;
            }
        }
        return $this->renderPartial('delivery-detail-part-view', ['track_record' => $track_record]);
    }

    //订单确认
    public function actionOrderForm()
    {
        $user = self::loginAuth();
        $institutionCode = Mall::getCurrentInstitutionCode();
        $userId = $user['id'];
        $cartGoodsList = MallFrontEnd::getCartSelected($userId);

        if (count($cartGoodsList) == 0) {
            return $this->redirect(['mall/cart', 'institution_code' => Mall::getCurrentInstitutionCode()]);
        }
//        $defaultAddress = MallFrontEnd::getDefaultAddress($userId);
        $addressList = MallFrontEnd::getUserAllAddress($userId);
        $userIntegral = User::getUserIntegral($userId);
        //是否有跨境电商商品
        $is_crossborder = 0;
        $selling_price_crossborder = 0;
        $sum_quantity = 0;
        $sum_integral = 0;
        foreach ($cartGoodsList as $cartGoods) {
            $sum_quantity = $sum_quantity + $cartGoods['quantity'];
            $sum_integral = $sum_integral + $cartGoods['selling_integral_sum'];
            if ($cartGoods['is_crossborder'] == '1') {
                $is_crossborder = 1;
                $selling_price_crossborder = $cartGoods['selling_price'] + $selling_price_crossborder;
            }
        }

        return $this->render('order-form', [
            'cartGoodsList' => $cartGoodsList,
            'addressList' => $addressList,
            'userIntegral' => $userIntegral,
            'is_crossborder' => $is_crossborder,
            'selling_price_crossborder' => $selling_price_crossborder,
            'sum_quantity' => $sum_quantity,
            'sum_integral' => $sum_integral,
        ]);
    }

    //订单提交 order-submit-handle(纯积分支付)
    public function actionOrderSubmitHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        if (MallFrontEnd::checkCartGoods($userId) > 0) {
            return $this->renderJson([], 1, '产品积分不能小于0');
        }
        $remark = Yii::$app->request->post('remark');
        $idcard_name = Yii::$app->request->post('idcard_name');
        $idcard_number = Yii::$app->request->post('idcard_number');
        $orderSubmitResult = MallFrontEnd::submitOrder($userId, $remark, $idcard_name, $idcard_number);

        return $this->renderJson(['orderSubmitResult' => $orderSubmitResult]);
    }

    //只生成订单 create-order-handle
    public function actionCreateOrderHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        if (MallFrontEnd::checkCartGoods($userId) > 0) {
            return $this->renderJson([], 1, '产品积分不能小于0');
        }
        $remark = Yii::$app->request->post('remark');
        $idcard_name = Yii::$app->request->post('idcard_name');
        $idcard_number = Yii::$app->request->post('idcard_number');

        $createOrderResult = MallFrontEnd::createOrder($userId, $remark, $idcard_name, $idcard_number);

        return $this->renderJson(['createOrderResult' => $createOrderResult]);
    }

    //只支付订单 pay-order-handle
    public function actionPayOrderHandle()
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        $orderId = Yii::$app->request->post('orderId');
        $payOrderResult = MallFrontEnd::payOrder($userId, $orderId);

        return $this->renderJson(['payOrderResult' => $payOrderResult]);
    }

    //取消订单 cancel-order-handle
    public function actionCancelOrderHandle()
    {
        self::loginAuth();
        $order_code = Yii::$app->request->post('order_code');
        $remark = Yii::$app->request->post('remark');
        $status = 1;
        $order = MallFrontEnd::getOrderByCode($order_code);
        $message = '';
        if ($order == false) {
            $message = '未找到此订单';
        } else {
            if ($order['status'] == '1') {
                $re_status = Order::cancelOrder($order_code, $remark);
//                var_dump($re_status);exit;
                // 0正常 20未找到此订单 21订单不能取消
                if ($re_status == '0') {
                    $message = '订单取消成功';
                    $status = 0;
                }
                if ($re_status == '20') {
                    $message = '未找到此订单';
                }
                if ($re_status == '21') {
                    $message = '订单不能取消';
                }

            } else {
                $message = '订单不能取消';
            }
        }
        return $this->renderJson([], $status, $message);
    }

    //支付成功页面
    public function actionPayOrderSuccess($orderId = false, $orderCode = false, $out_trade_no = false)
    {
        if ($orderCode == false && $orderId == false && $out_trade_no == false) {
            throw new \Exception('param error!');
        }
        if ($orderId) {
            $orderInfo = MallFrontEnd::getOrderById($orderId);
            if ($orderInfo == false) {
                throw new \Exception('order not found!1');
            }
            $orderCode = $orderInfo['code'];
        }
        if ($out_trade_no) {
            $re = Pay::getPayIntegralRecord($out_trade_no);
            if ($re == false) {
                throw new \Exception('order not found!2');
            }
            $orderCode = $re['order_code'];
        }
        self::authOrder($orderCode);
        $orderInfo = MallFrontEnd::getOrderByCode_detail($orderCode);
        return $this->render('pay-order-success', [
            'orderInfo' => $orderInfo,
        ]);
    }

    /**校验订单是否是当前用户的
     * @param $orderCode
     * @throws \Exception
     */
    private function authOrder($orderCode)
    {
        $user = self::loginAuth();
        $userId = $user['id'];
        if (MallFrontEnd::checkOrderOwner($userId, $orderCode) == false) {
            throw new \Exception('orderCode error!');
        }
    }

    public function actionHomeLogin()
    {
        $this->layout = false;
        Yii::$app->session->remove('normal-login-phone');
        return $this->render('home-login', []);
    }

    //home-vip-login-handle
    public function actionHomeVipLoginHandle()
    {
        $voucher = Yii::$app->request->post('card_voucher');
        $token = Yii::$app->request->post('card_token');
        $phone = \Yii::$app->request->post('phone');
        $verificationCode = \Yii::$app->request->post('verification_code');
        $result = User::authSmsVerificationCode($phone, $verificationCode);
        //调试用
//        $result=true;
        if ($result == false) {
            return $this->renderJson(null, 1, '验证码错误');
        }
        try {
            $voucherItem = Voucher::authVoucher($voucher, $token);
            $card = Voucher::getCardByVoucher($voucher);
            if ($card == null) {
                throw new \Exception('卡片信息获取失败!');
            }
            //创建用户
            $user = User::getUserByPhone($card['to_institution_code'], $phone);
            if ($user == null) {
                $data = [
                    'id' => '0',
                    'code' => '',
                    'name' => $phone,
                    'institution_code' => $card['to_institution_code'],
                    'phone' => $phone,
                    'isEnabled' => 1,
                    'remark' => '',
                    'wx_openid' => '',
                    'header_url' => ''
                ];
                User::addUser($data);
                $user = User::getUserByPhone($card['to_institution_code'], $phone);
            } else {
                //pass
            }
            //注册session
            Mall::setCurrentInstitutionByCode($card['to_institution_code']);//为了beforeAction不清除session
            Mall::setCurrentUser($user);
            //用卡
            if ($voucherItem['status'] == 2) {
                $status = Voucher::useVoucher($voucherItem['voucher'], $user['id']);
                if ($status != 0) {
                    throw new \Exception('获取积分失败!');
                }
            }
        } catch (\Exception $e) {
            return $this->renderJson(null, 1, $e->getMessage());
        }

        return $this->renderJson(["institution_code" => $card['to_institution_code'], 'card_id' => $card['id']]);
    }

    //home-normal-login-handle
    public function actionHomeNormalLoginHandle()
    {
        $phone = \Yii::$app->request->post('phone');
        $verificationCode = \Yii::$app->request->post('verification_code');
        $result = User::authSmsVerificationCode($phone, $verificationCode);
        //调试用
//        $result=true;
        if ($result == false) {
            return $this->renderJson(null, 1, '验证码错误');
        }
        Yii::$app->session->set('normal-login-phone', $phone);
        return $this->renderJson();
    }

    public function actionInstList()
    {
        $phone = Yii::$app->session->get('normal-login-phone', false);
        if ($phone == false) {
            return $this->redirect('home-login');
        }
        $this->layout = false;
        $instList = User::getInstitutionListByPhone($phone);
//        var_dump($instList);exit;
        return $this->render('inst-list', [
            'instList' => $instList,
        ]);
    }

    //redirect-inst-index
    public function actionRedirectInstIndex($institution_code)
    {
        $phone = Yii::$app->session->get('normal-login-phone', false);
        if ($phone == false) {
            return $this->redirect('home-login');
        }
        $user = User::getUserByPhone($institution_code, $phone);
        if ($user['is_enabled'] == 0) {
            throw new \Exception('此用户已被禁用!');
        }
        //注册session
        Mall::userLogout();
        Mall::removeCurrentCard();
        Mall::removeCurrentVoucher();
        self::removeCardSession();
        Mall::setCurrentUser($user);
        return $this->redirect(['index', 'institution_code' => $institution_code]);
    }

    //home-send-login-sms-verification-code-handle
    public function actionHomeSendLoginSmsVerificationCodeHandle()
    {
        $phone = \Yii::$app->request->post('phone');
        $type = \Yii::$app->request->post('type');
        try {
            $is_send = false;
            if ($type == 'vip') {
                $is_send = true;
            }
            if ($type == "normal") {
                $instList = User::getInstitutionListByPhone($phone);
                if (count($instList) == 0) {
                    throw new \Exception('无此用户或者用户已经被禁用!');
                } else {
                    $is_send = true;
                }
            }

            if ($is_send) {
                User::sendSmsVerificationCode($phone);
                return $this->renderJson();
            } else {
                return $this->renderJson(null, 1, '类型不对，不能发送');
            }
        } catch (\Exception $ex) {
            return $this->renderJson(null, 1, $ex->getMessage());
        }
    }

    /**
     * 手机话费充值
     * @return string
     */
    public function actionPhoneRecharge()
    {
        return $this->render('phone-recharge');
    }

    public function actionPhoneRechargeHandler()
    {
        $phone = Yii::$app->request->post('phone');
        $huafeiduo = new Huafeiduo();
        $result = $huafeiduo->check(1, $phone);
        if ($result == false) {
            return $this->renderJson(null, 1, '此手机不能进行充值');
        }
        $result = $huafeiduo->submit(1, $phone, $phone . time());
        if ($result == false) {
            return $this->renderJson(null, 2, '充值失败');
        }

        return $this->renderJson(null);
    }
}